<template>
  <div>
    <!-- 查询区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-card>
        <el-input
          style="width: 200px; margin-right: 10px"
          v-model="a_user.name"
          placeholder="请输入名字查询"
          prefix-icon="Search"
        />
        <el-input
          style="width: 200px; margin-right: 10px"
          v-model="a_user.id"
          placeholder="请输入ID查询"
          prefix-icon="Search"
        />
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
        <el-button type="info" @click="$router.go(-1)">返 回</el-button>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table
        :data="a_user.tableData"
        border
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" type="index" width="60" />
        <el-table-column label="uid" prop="uid" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="账号" prop="account" />
        <el-table-column label="密码" prop="password" />
        <el-table-column label="性别" prop="gender" />
        <el-table-column label="年龄" prop="age" />
        <el-table-column label="会员等级" prop="title" />

        <!-- 操作列 -->
        <el-table-column label="操作">
          <template #default="scope">
            <div style="display: flex; flex-direction: column; align-items: center; gap: 5px;">
              <div>
              <el-button
                type="primary"
                :icon="Edit"
                size="small"
                style="width: 80px; text-align: center; border-radius: 4px;"
                @click="handleEdit(scope.row)"
              >
                <span style="margin-left: 5px;">编辑</span>
              </el-button>
              </div>
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                style="width: 80px; text-align: center; border-radius: 4px;"
                @click="handleDelete(scope.row)"
              >
                                <span style="margin-left: 5px;">删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
          @size-change="load"
          @current-change="load"
          v-model:current-page="a_user.pageNumber"
          v-model:page-size="a_user.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="a_user.total"
          background
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="a_user.form.uid ? '编辑会员' : '新增会员'" v-model="a_user.formVisible" width="500">
      <el-form :model="a_user.form" style="padding-right: 50px; padding-top: 20px;">
        <el-form-item label="姓名" label-width="80px">
          <el-input v-model="a_user.form.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="账号" label-width="80px">
          <el-input v-model="a_user.form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" label-width="80px">
          <el-input v-model="a_user.form.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="性别" label-width="80px">
          <el-radio-group v-model="a_user.form.gender">
            <el-radio value="M" label="M">男</el-radio>
            <el-radio value="F" label="F">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" label-width="80px">
          <el-input v-model.number="a_user.form.age" placeholder="请输入年龄" type="number" />
        </el-form-item>
        <el-form-item label="会员等级" label-width="80px">
          <el-select v-model="a_user.form.title" placeholder="请选择会员等级" style="width: 100%">
            <el-option label="正式会员" value="正式会员" />
            <el-option label="高级会员" value="高级会员" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="a_user.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'

const route = useRoute()

const a_user = reactive({
  name: '',
  id: '',
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  tableData: [],
  formVisible: false,
  form: {},
  selectedRows: []
})

//  首先定义 load 函数，避免在 watch 中引用未定义的函数
const load = () => {
  request.get('/v1/admin/selectPage', {
    params: {
      tableName: 'user',
      name: a_user.name,
      id: a_user.id, // 使用 uid 作为查询条件
      pageNum: a_user.pageNumber,
      pageSize: a_user.pageSize
    }
  }).then(res => {
    if (res.state === 2001) {
      a_user.tableData = res.data.list || []
      a_user.total = res.data.total || 0
    } else {
      a_user.tableData = []
      a_user.total = 0
    }
  }).catch(error => {
    console.error('请求失败:', error)
    a_user.tableData = []
    a_user.total = 0
  })
}

// 监听路由参数变化
watch(() => route.params.uid, (newUid) => {
  if (newUid) {
    a_user.id = newUid // 将 uid 赋值给查询条件
    load() // 触发查询
  }
}, { immediate: true })

// 重置查询条件
const reset = () => {
  a_user.name = ''
  a_user.id = ''
  load()
}

// 处理新增
const handleAdd = () => {
  a_user.form = {
    username: '',
    account: '',
    password: '',
    gender: 'M',
    age: '',
    title: '正式会员'
  }
  a_user.formVisible = true
}

// 处理编辑
const handleEdit = (row) => {
  a_user.form = { ...row } // 填充当前行数据
  a_user.formVisible = true // 打开对话框
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/delete', {
      data: {
        tableName: 'user',
        id: row.uid // 使用 uid 作为删除依据
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '删除成功', type: 'success' })
        load() // 重新加载数据
      } else {
        ElMessage({ message: '删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (a_user.selectedRows.length === 0) {
    ElMessage({ message: '请选择要删除的用户', type: 'warning' })
    return
  }

  ElMessageBox.confirm('确定要删除这些用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = a_user.selectedRows.map(row => row.uid) // 获取所有选中行的 uid
    request.delete('/v1/admin/batchDelete', {
      data: {
        tableName: 'user',
        ids: ids // 传递要删除的 uid 列表
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '批量删除成功', type: 'success' })
        load() // 重新加载数据
      } else {
        ElMessage({ message: '批量删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理用户选择的行数据
const handleSelectionChange = (rows) => {
  a_user.selectedRows = rows
}

// 保存新增或编辑
const save = () => {
  // 校验必填字段
  if (!a_user.form.username || !a_user.form.account || !a_user.form.password) {
    ElMessage({ message: '姓名、账号和密码不能为空', type: 'error' })
    return
  }

  const method = a_user.form.uid ? 'put' : 'post'
  const url = a_user.form.uid ? '/v1/admin/update' : '/v1/admin/add'

  request[method](url, {
    tableName: 'user',
    data: {
      ...a_user.form,
      // 确保字段名对应数据库表 user 的列名
      uid: a_user.form.uid || undefined, // 新增时不要传 uid
      username: a_user.form.username,
      account: a_user.form.account,
      password: a_user.form.password,
      gender: a_user.form.gender,
      age: a_user.form.age,
      title: a_user.form.title
    }
  }).then(res => {
    if (res.state === 2001) {
      ElMessage({
        message: a_user.form.uid ? '编辑成功' : '新增成功',
        type: 'success'
      })
      a_user.formVisible = false
      load()
    } else {
      ElMessage({
        message: a_user.form.cid ? '编辑失败' : '新增失败',
        type: 'error'
      })
    }
  }).catch(error => {
    console.error('请求失败:', error)
    ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
  })
}

// 初始化加载数据
onMounted(() => {
  load()
})
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
</style>
